<?php
namespace app\admin\model;
use think\Model;
class Banner extends Model
{
    protected static function init()
    {
        //新增前
        Banner::event('before_insert',function ($data){
            if ($_FILES['thumb']['tmp_name']){
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public' . DS .'static/uploads');
                if ($info){
                    $thumb = '/static/uploads'.'/'.$info->getSaveName();
                    $data['thumb'] = $thumb;
                }
            }
        });

        //（3.16注释）更新前
//      Banner::event('before_update',function ($data){
//          if ($_FILES['thumb']['tmp_name']){
//              $arts = Banner::find($data->id);
////                echo $_SERVER['DOCUMENT_ROOT'];die;
//              $thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
//              if (file_exists($thumbpath)){
//                  @unlink($thumbpath);
//              }
//              $file = request()->file('thumb');
//              $info = $file->move(ROOT_PATH . 'public' . DS .'static/uploads');
//              if ($info){
//                  $thumb = '/static/uploads'.'/'.$info->getSaveName();
//                  $data['thumb'] = $thumb;
//              }
//          }
//      });

        //删除前
        Banner::event('before_delete',function ($data){
            $arts = Banner::find($data->id);
            $thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
            if (file_exists($thumbpath)){
                @unlink($thumbpath);
            }
        });
    }
}

